package com.ys.controller.api.storage;

import com.ys.config.MenuId;
import com.ys.entity.storage.TccLogisticsPaymentTariff;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.flow.YspTaskService;
import com.ys.service.storage.TccLogisticsPaymentTariffService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Author: xjx
 * @CreateTime: 2025-3-04
 * @Description: 物流付款单（关税费）
 * @Version: 1.5
 */
@Controller
@RequestMapping("/api/inter/tccLogisticsPaymentTariff")
public class ApiInterTccLogisticsPaymentTariffController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTccLogisticsPaymentTariffController.class);

    @Autowired
    private TccLogisticsPaymentTariffService tccLogisticsPaymentTariffService;

    @Autowired
    private CommonApiService<TccLogisticsPaymentTariff> commonApiService;

    @Autowired
    private YspTaskService yspTaskService;
    //菜单id
    private Long menuId = MenuId.TCC_LogisticsPaymentTariff;


    //权限字符
    private final String PERMISSIONS_VIEW = "tccLogisticsPaymentTariff:view";
    private final String PERMISSIONS_ADD = "tccLogisticsPaymentTariff:add";

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TccLogisticsPaymentTariff setSeachSql(TccLogisticsPaymentTariff cond){

        cond
               // .addField("CASE WHEN  A.EffectStock = 1 THEN FORMAT(A.UpdateTime, 'yyyy-MM-dd HH:mm:ss') ELSE null END _ys_effectiveTime")//生效时间
                .addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人

                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS _ys_auditingTime")//审核时间

            .addLeftJoin("TCC_LogisticsPaymentTariffItem SA ON SA.Pbid = A.Bid")//子表
                .addField("SA.PayAmount AS payAmount")
                .addField("SA.LogOrderlDesDz AS logOrderlDesDz")

            .addLeftJoin("TCC_LogisticsComprehensive SB ON SB.LogInvoiceNo = SA.LogInvoiceNo")//物流信息表
                .addField("SB.FbaNo AS fbaNo") //FBA编号
                .addField("SB.SpOrderBid AS spOrderBid") // 服务商订单号
                .addField("SB.ServiceTariff AS serviceTariff")//        服务商关税费用（导入）
                .addField("SB.RateDuty AS rateDuty")//        关税利率
                .addField("SB.SpTariffAmount AS spTariffAmount")//        服务商关税金额（支付）
                .addField("SB.LogInvoiceCost AS logInvoiceCost")//        物流发票费用（总）
                .addField("SB.LogInvoiceSalesFee AS logInvoiceSalesFee")//        物流销售费用（总）
                .addField("SB.LogChannelName AS logChannelName")//        物流渠道名称
                .addField("SB.FbaDeliverBid AS fbaDeliverBid")//                FBA发货单号
                .addField("SB.FbaBoxUpBid AS fbaBoxUpBid")//        FBA装箱单号
                .addField("SB.FbaPlanBid AS fbaPlanBid")//        FBA计划单号

                .addLeftJoin("TCC_FbaPlan SC ON SC.Bid = SB.FbaPlanBid")//FBA计划
                .addField("SC.DeliverState AS deliverState")//               发货计划（1按SKU自动发货，0按箱自动发货）
                .addField("CASE WHEN SC.DeliverState = 1 THEN '按SKU自动发货'  ELSE '按箱自动发货' END deliverStateTxt")// 发货计划（1按SKU自动发货，0按箱自动发货）

                .addField("SC.Vgsbm AS vgsbm")//        运营公司编码
                .addField("SC.VgsJc AS vgsJc")//                运营公司简称
                .addField("SC.DeclarationState AS declarationState")//                是否报关
                .addField("CASE WHEN SC.DeclarationState = 1 THEN '是'  ELSE '否' END declarationStateTxt")// 是否报关


                .addField("SC.ShopName AS shopName")//                网店名称

                .addLeftJoin("TCC_FbaDeliverItem SD ON SD.Id = SB.FbaDeliverItemId")//FBA发货单号详情id（TCC_FbaDeliverItem）
                .addLeftJoin("TCC_FbaBoxUpInfo SE ON SE.Id = SD.FbaBoxUpInfoId")//装箱单FBA信息
                .addField("SE.FbaWarehouse AS fbaWarehouse")//        FBA仓库
                .addField("SE.FbaTrackNo AS fbaTrackNo")//        FBA追踪编号

                .addLeftJoin("TCC_LogisticsChannelDetail SF ON SF.LogInvoiceNo = SB.LogInvoiceNo")//物流渠道详情表
                .addField("SF.LogsticsWay AS logsticsWay")// 物流服务名称


                .where("SB.IsFirstByInvoice = 1")//是否是同一发票中的第一条（0否1是）

        ;

        cond.setOrderby("A.Bid DESC");//排序

        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }


    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute TccLogisticsPaymentTariff cond, String conditions){
       
        cond = setSeachSql(cond);
        String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
        if (nameLinked != null){
            cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
        }
        String _ys_auditingTime = ConditionUtil.getConditionValue(conditions, "_ys_auditingTime");//审核时间
        if (_ys_auditingTime != null && _ys_auditingTime.length() > 0) {
            String[] timeDays = _ys_auditingTime.split(" ~ ");
            cond.where("P.UpdateTime >= '" + timeDays[0] + "' and P.UpdateTime <= '" + timeDays[1] + "'");
        }

        LayuiTableVoJA vo = commonApiService.searchLay(cond);
        return vo;
    }



    /*
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccLogisticsPaymentTariff cond, String conditions) throws Exception{

        cond = setSeachSql(cond);

        String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
        if (nameLinked != null){
            cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
        }
        String _ys_auditingTime = ConditionUtil.getConditionValue(conditions, "_ys_auditingTime");//审核时间
        if (_ys_auditingTime != null && _ys_auditingTime.length() > 0) {
            String[] timeDays = _ys_auditingTime.split(" ~ ");
            cond.where("P.UpdateTime >= '" + timeDays[0] + "' and P.UpdateTime <= '" + timeDays[1] + "'");
        }
        cond.setPage(0).setSize(999999);

        List<Map<String, Object>> listData = cond.queryMap();

        List<YsCol> listField = new YsCol()
                .setMenuId(MenuId.TCC_LogisticsPaymentTariff)
                .setFrontExport(YsColEnum.FrontShow.SHOW.value)
                .setOrderby("A.SortNo asc")
                .queryList();


        ExportExcelUtils<TccLogisticsPaymentTariff> util = new ExportExcelUtils<TccLogisticsPaymentTariff>(new TccLogisticsPaymentTariff());

        String toFilePath = util.exportExcel(listData, listField, "物流付款单（关税费）");
        UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }





    /**
     * 新增
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tccLogisticsPaymentTariffService.add(params,menuId);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(e.getMessage());
        }
    }

    /**
     * 修改
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            return tccLogisticsPaymentTariffService.toEdit(params,menuId);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 删除
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/deleteTrue")
    @ResponseBody
    public R deleteTrue(Long id){
        try {
            //删除
            return tccLogisticsPaymentTariffService.deleteTrue(id);
        } catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            throw new RuntimeException(e.getMessage());
        }
    }


    /**
     * 流转通过
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            TccLogisticsPaymentTariff entity = new TccLogisticsPaymentTariff().setId(id).queryFirst();
            return tccLogisticsPaymentTariffService.flowPass(entity.getBid(), ShiroUtils.getUserId());
        } catch(IllegalArgumentException e){
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 流转退回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){
        try {
            TccLogisticsPaymentTariff entity = new TccLogisticsPaymentTariff().setId(id).queryFirst();
            return yspTaskService.flowRefuse(entity.getBid(), reason,ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 流转驳回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){
        try {
            TccLogisticsPaymentTariff entity = new TccLogisticsPaymentTariff().setId(id).queryFirst();
            return yspTaskService.flowInit(entity.getBid(), reason,ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }







}
